// Toast 服务
import { createApp, type App } from "vue";
import Toast from "@/components/Toast.vue";

class ToastService {
  private toastInstance: any = null;
  private toastApp: App | null = null;

  init() {
    if (this.toastInstance) return;

    // 创建Toast容器
    const container = document.createElement("div");
    container.id = "toast-container";
    document.body.appendChild(container);

    // 创建Toast应用实例
    this.toastApp = createApp(Toast);
    this.toastInstance = this.toastApp.mount(container);
  }

  success(message: string, title?: string, duration?: number) {
    this.init();
    this.toastInstance?.success(message, title, duration);
  }

  error(message: string, title?: string, duration?: number) {
    this.init();
    this.toastInstance?.error(message, title, duration);
  }

  warning(message: string, title?: string, duration?: number) {
    this.init();
    this.toastInstance?.warning(message, title, duration);
  }

  info(message: string, title?: string, duration?: number) {
    this.init();
    this.toastInstance?.info(message, title, duration);
  }

  destroy() {
    if (this.toastApp) {
      this.toastApp.unmount();
      this.toastApp = null;
    }
    if (this.toastInstance) {
      this.toastInstance = null;
    }
    const container = document.getElementById("toast-container");
    if (container) {
      document.body.removeChild(container);
    }
  }
}

export const toast = new ToastService();

// 便捷方法
export const showToast = {
  success: (message: string, title?: string) => toast.success(message, title),
  error: (message: string, title?: string) => toast.error(message, title),
  warning: (message: string, title?: string) => toast.warning(message, title),
  info: (message: string, title?: string) => toast.info(message, title),
};

// 替换 ElMessage 的便捷方法
export const Message = {
  success: (message: string) => toast.success(message, "成功"),
  error: (message: string) => toast.error(message, "错误"),
  warning: (message: string) => toast.warning(message, "警告"),
  info: (message: string) => toast.info(message, "提示"),
};
